/**
 * Created by huangwei on 2017/3/22.
 */

const key = "goods";

/**
 * 将传过来的商品对象,保存到localstorage中
 * */
export function saveGoods(goodsObj) {
    //1.通过key，从localstoryage中将原来的数据读取出来
    var goodsList = JSON.parse(localStorage.getItem(key) || '[]')

    //2.拼接好数据
    if (goodsList.length <=0){
        goodsList.push(goodsObj);
    }else{
        var isExist = true;

        for(var i=0;i<goodsList.length;i++){
            if (goodsList[i].goodsId==goodsObj.goodsId){
                goodsList[i].count += goodsObj.count;
                isExist = true;
                break;
            }else{
                isExist = false;
            }
        }

        if (!isExist){
            goodsList.push(goodsObj);
        }
    }
    //goodsList.push(goodsObj);

    //3.以覆盖的形式写入
    localStorage.setItem(key,JSON.stringify(goodsList));
}

//返回购物车中所有商品的总数,方便第一次进来的时候，改变App.vue中购物车的徽标
export function getGoodsTotalCount() {
    var goodsList = JSON.parse(localStorage.getItem(key) || '[]');

    var totalCount = 0;
    goodsList.forEach(goods=>{
        totalCount+=goods.count;
    })

    return totalCount;
}

//获取localStorage中的商品的列表
export function getGoodsList() {
    return JSON.parse(localStorage.getItem(key) || '[]');
}

//获取某个id对应的商品数量
export function getCountByGoodsId(goodsId) {
    var goodsCount = 0;

    var goodsList = JSON.parse(localStorage.getItem(key) || '[]');

    for(var i=0;i<goodsList.length;i++){
        if (goodsId==goodsList[i].goodsId){
            goodsCount = goodsList[i].count;
            break;
        }
    }

    return goodsCount;
}